/*
 * Copyright (c) 1994, 2021, Oracle and/or its affiliates. All rights reserved.
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Oracle designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Oracle in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */
package com.i360day.invoker;

import com.i360day.invoker.codes.encoder.Encoder;
import com.i360day.invoker.common.HttpInvokerRemoteConstant;
import com.i360day.invoker.exception.AnalysisException;
import com.i360day.invoker.properties.HttpInvokerProperties;
import com.i360day.invoker.support.RemoteInvocation;
import com.i360day.invoker.support.RemoteInvocationFactory;
import com.i360day.invoker.support.RemoteInvocationResult;
import com.i360day.invoker.support.RemoteInvocationSerializingExporter;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisConnectionFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.Type;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author: liju.z
 * @date: 2024/3/20 11:08
 */
public class RedisInvokerServiceExporter extends RemoteInvocationSerializingExporter implements InitializingBean, SmartInitializingSingleton {
    private final RemoteInvocationFactory remoteInvocationFactory;
    private final Encoder encoder;
    private final RedisConnectionFactory redisConnectionFactory;
    private final HttpInvokerProperties httpInvokerProperties;
    private String exchangeKey;
    private String routingKey;
    private String queueKey;
    private int listenerCount = 1;

    public RedisInvokerServiceExporter(HttpInvokerProperties httpInvokerProperties, Encoder encoder, RemoteInvocationFactory remoteInvocationFactory, RedisConnectionFactory redisConnectionFactory) {
        this.httpInvokerProperties = httpInvokerProperties;
        this.encoder = encoder;
        this.remoteInvocationFactory = remoteInvocationFactory;
        this.redisConnectionFactory = redisConnectionFactory;
    }

    public void setExchangeKey(String exchangeKey) {
        this.exchangeKey = exchangeKey;
    }

    public void setRoutingKey(String routingKey) {
        this.routingKey = routingKey;
    }

    public void setQueueKey(String queueKey) {
        this.queueKey = queueKey;
    }

    @Override
    public void afterPropertiesSet() {
        super.afterPropertiesSet();
    }

    @Override
    public void afterSingletonsInstantiated() {
        RedisConnection connection = redisConnectionFactory.getConnection();
        connection.subscribe((message, pattern) -> {
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                RedisRequest redisRequest = getRedisRequest(connection, message);
                try {
                    //analysis
                    ObjectInputStream objectInputStream = createObjectInputStream(new ByteArrayInputStream(redisRequest.getBody()));
                    RemoteInvocation invocation = remoteInvocationFactory.doReadRemoteInvocation(objectInputStream);
                    Type returnType = invocation.getReturnType(getService());

                    //invoke
                    RemoteInvocationResult result = invokeAndCreateResult(invocation, getProxy());
                    encoder.writeRemoteInvocationResult(outputStream, returnType == null ? Object.class : returnType, result);
                } catch (Exception ex) {
                    outputStream.write(Optional.ofNullable(ex.getMessage()).orElse("调用出错").getBytes());
                }
                connection.publish(redisRequest.getReplyTo().getBytes(), outputStream.toByteArray());
            } catch (Exception ex) {
                if (!(ex instanceof AnalysisException)) {
                    logger.error("redis server execute fail", ex);
                }
            }
        }, routingKey.getBytes());
    }

    private RedisRequest getRedisRequest(RedisConnection connection, Message message) throws AnalysisException {
        CompletableFuture<RedisRequest> completableFuture = new CompletableFuture();
        Boolean exist = connection.setNX(message.getChannel(), message.getBody());
        try {
            if (exist) {
                connection.expire(message.getChannel(), httpInvokerProperties.getReadTimeout() / 1000);
                completableFuture.complete(HttpInvokerRemoteConstant.objectMapper.readValue(message.getBody(), RedisRequest.class));
            } else {
                completableFuture.cancel(true);
            }
            return completableFuture.get(httpInvokerProperties.getReadTimeout(), TimeUnit.MILLISECONDS);
        } catch (Exception ex) {
            throw new AnalysisException(ex);
        } finally {
            connection.del(message.getChannel());
        }
    }
}
